package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zbkj.dal.base.page.CommonPage;
import com.zbkj.dal.dao.ProductBrandDao;
import com.zbkj.dal.dao.SystemBankInfoDao;
import com.zbkj.dal.entity.product.ProductBrand;
import com.zbkj.dal.entity.system.SystemBankInfo;
import com.zbkj.dal.pojo.request.PageParamRequest;
import com.zbkj.service.model.vo.BankListVO;
import com.zbkj.service.model.vo.BrandGroupVO;
import com.zbkj.service.service.MetaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MetaServiceImpl implements MetaService {

    @Resource
    private ProductBrandDao productBrandDao;

    @Resource
    private SystemBankInfoDao systemBankInfoDao;

    @Override
    public CommonPage<BankListVO> bankList(PageParamRequest request) {
        PageHelper.startPage(request.getPage(), request.getLimit());
        List<SystemBankInfo> systemBankInfos = systemBankInfoDao.selectList(new LambdaQueryWrapper<>());
        CommonPage<SystemBankInfo> systemBankInfoCommonPage = CommonPage.restPage(systemBankInfos);
        CommonPage<BankListVO> result = new CommonPage<>();
        result.setPage(systemBankInfoCommonPage.getPage());
        result.setLimit(systemBankInfoCommonPage.getLimit());
        result.setTotalPage(systemBankInfoCommonPage.getTotalPage());
        result.setTotal(systemBankInfoCommonPage.getTotal());
        List<BankListVO> bankListVOS = systemBankInfos.stream().map(info -> {
            BankListVO bankListVO = new BankListVO();
            bankListVO.setBankName(info.getBankName());
            bankListVO.setBankCode(info.getBankNumber());
            bankListVO.setBankIcon(info.getIcon());
            return bankListVO;
        }).collect(Collectors.toList());
        result.setList(bankListVOS);
        return result;
    }

    @Override
    public List<BrandGroupVO> brandList() {
        LambdaQueryWrapper<ProductBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductBrand::getIsShow, true);
        wrapper.eq(ProductBrand::getIsDel, false);
        List<ProductBrand> productBrands = productBrandDao.selectList(wrapper);

        List<BrandGroupVO> brandGroups = new ArrayList<>();
        Map<String, List<ProductBrand>> brandGroup = productBrands.stream().collect(Collectors.groupingBy(brand -> brand.getNamePy().substring(0, 1)));
        brandGroup.forEach((k, v) -> brandGroups.add(BrandGroupVO.generate(k, v)));
        return brandGroups.stream().sorted(Comparator.comparing(BrandGroupVO::getGroupKey)).collect(Collectors.toList());
    }
}
